<template>
  <div>
    <div style="width: 40%; margin: 20px auto; font-size: 20px" class="card">修改密码</div>
    <div style="width: 40%; margin: 25px auto" class="card">
      <el-form :model="user"
               :rules="rules"
               ref="formRef"
               label-width="80px"
               style="padding: 20px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="user.oldPassword" placeholder="请输入原密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="user.newPassword" placeholder="请输入新密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="user.confirmPassword" placeholder="请确认新密码" show-password></el-input>
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" @click="edit">保 存</el-button>
          <el-button type="info" @click="router.back()">返 回</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import router from '@/router/index.js'
import useUserStore from '@/store/user.js'
import { updatePassword } from '@/api/User.js'

const userStore = useUserStore()

const formRef = ref()
const { proxy } = getCurrentInstance()

const user = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入确认密码'))
  }
  if (value !== user.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ]
}

const edit = () => {
  proxy.$refs.formRef.validate(valid => {
    console.log(1)
    if (valid) {
      console.log(2)
      updatePassword(user).then(res => {
        if (res.code === 1) {
          ElMessage.success('修改成功')
          router.go(-1)
        }
      })
    }
  })
}
</script>

<style scoped lang="scss">
.card {
  background-color: #fff;
  border-radius: 5px;
  padding: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, .1);
}
</style>
